package com.yu.init.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yu.init.annotation.AuthCheck;
import com.yu.init.common.BaseResponse;
import com.yu.init.common.DeleteRequest;
import com.yu.init.common.ErrorCode;
import com.yu.init.common.ResultUtils;
import com.yu.init.constant.UserConstant;
import com.yu.init.exception.BusinessException;
import com.yu.init.exception.ThrowUtils;
//import com.yu.init.manager.RedisLimiterManager;
import com.yu.init.manager.SparkManager;
import com.yu.init.model.dto.feed.*;
import com.yu.init.model.entity.Feed;
import com.yu.init.model.entity.User;
import com.yu.init.service.FeedService;
import com.yu.init.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 留言反馈接口
 *

 */
@RestController
@RequestMapping("/feed")
@Slf4j
public class FeedController {

    @Resource
    private FeedService feedService;

    @Resource
    private UserService userService;


//    @Resource
//    private RedisLimiterManager redisLimiterManager;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

//    @Resource
//    private BiMessageProducer biMessageProducer;

    @Resource
    private SparkManager sparkManager;


    // region 增删改查

    /**
     * 创建
     *
     * @param feedAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addFeed(@RequestBody FeedAddRequest feedAddRequest, HttpServletRequest request) {
        // 检查请求参数是否为空
        if (feedAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Feed feed = new Feed(); // 创建Feed对象
        BeanUtils.copyProperties(feedAddRequest, feed);
        // 获取当前登录用户ID
        User loginUser = userService.getLoginUser(request);
//        if (loginUser == null) {
//            throw new BusinessException(ErrorCode.USER_NOT_LOGGED_IN);
//        }
        // 设置用户ID到Feed对象中
        feed.setUserId(loginUser.getId());
        // 保存Feed（留言反馈）
        boolean result = feedService.save(feed);
        // 检查保存是否成功
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 获取新保存的Feed的ID
        long newFeedId = feed.getFeedId();
        // 返回成功响应，包含新Feed的ID
        return ResultUtils.success(newFeedId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteFeed(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Feed oldFeed = feedService.getById(id);
        ThrowUtils.throwIf(oldFeed == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldFeed.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = feedService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param feedUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateFeed(@RequestBody FeedUpdateRequest feedUpdateRequest) {
        // 检查请求参数是否为空或者ID是否合法
        if (feedUpdateRequest == null || feedUpdateRequest.getFeedid() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 创建Feed对象，并从请求中复制属性
        Feed feed = new Feed();
        BeanUtils.copyProperties(feedUpdateRequest, feed);

        long id = feedUpdateRequest.getFeedid();
        // 获取要更新的留言反馈对象
        Feed oldFeed = feedService.getById(id);
        ThrowUtils.throwIf(oldFeed == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = feedService.updateById(feed);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<Feed> getFeedById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Feed feed = feedService.getById(id);
        if (feed == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(feed);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param feedQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<Feed>> listFeedByPage(@RequestBody FeedQueryRequest feedQueryRequest,
                                                   HttpServletRequest request) {
        long current = feedQueryRequest.getCurrent();
        long size = feedQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Feed> feedPage = feedService.page(new Page<>(current, size),
                feedService.getFeedByWrapper(feedQueryRequest));
        return ResultUtils.success(feedPage);
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param feedQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page")
    public BaseResponse<Page<Feed>> listMyFeedByPage(@RequestBody FeedQueryRequest feedQueryRequest,
            HttpServletRequest request) {
        if (feedQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        feedQueryRequest.setUserId(loginUser.getId());
        long current = feedQueryRequest.getCurrent();
        long size = feedQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Feed> feedPage = feedService.page(new Page<>(current, size),
                feedService.getFeedByWrapper(feedQueryRequest));
        return ResultUtils.success(feedPage);
    }



    // endregion

    /**
     * 编辑（用户）
     *
     * @param feedEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editFeed(@RequestBody FeedEditRequest feedEditRequest, HttpServletRequest request) {
        if (feedEditRequest == null || feedEditRequest.getFeedid() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Feed feed = new Feed();
        BeanUtils.copyProperties(feedEditRequest, feed);
        User loginUser = userService.getLoginUser(request);
        long id = feedEditRequest.getFeedid();
        // 判断是否存在
        Feed oldFeed = feedService.getById(id);
        ThrowUtils.throwIf(oldFeed == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldFeed.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = feedService.updateById(feed);
        return ResultUtils.success(result);
    }

//    /**
//     * 获取查询包装类
//     *
//     * @param feedQueryRequest
//     * @return
//     */
//    private QueryWrapper<Feed> getQueryWrapper(FeedQueryRequest feedQueryRequest) {
//        QueryWrapper<Feed> queryWrapper = new QueryWrapper<>();
//        if (feedQueryRequest == null) {
//            return queryWrapper;
//        }
//        Long id = feedQueryRequest.getId();
//        String name = feedQueryRequest.getName();
//        String goal = feedQueryRequest.getGoal();
//        String feedType = feedQueryRequest.getFeedType();
//        Long userId = feedQueryRequest.getUserId();
//        String sortField = feedQueryRequest.getSortField();
//        String sortOrder = feedQueryRequest.getSortOrder();
//
//        queryWrapper.eq(id != null && id > 0, "id", id);
//        queryWrapper.like(StringUtils.isNotBlank(name), "name", name);
//        queryWrapper.eq(StringUtils.isNotBlank(goal), "goal", goal);
//        queryWrapper.eq(StringUtils.isNotBlank(feedType), "feedType", feedType);
//        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
//        queryWrapper.eq("isDelete", false);
//        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
//                sortField);
//        return queryWrapper;
//    }


}
